<template>
	<view class="pb-safe-nopadding">
		<view class="bg-[#FFFFFF] px-[16px] py-[4px]" v-if="list.length > 0">
			<u-search v-model="keyword" action-text="取消" @custom="clear" :showAction="!!keyword"></u-search>
		</view>
		<u-cell  @click="itemClick(item)" class="bg-[#FFFFFF]" v-for="(item,index) in showList" :key="index" rightIcon="edit-pen" isLink :rightIconStyle="{fontSize:'24px'}">
			<template v-slot:title>
				<view class="flex flex-row text-[16px] text-[#333333]">
					<text>{{item.LinkMan}}</text>
					<text class="flex-shrink-0 ml-[16px]">{{item.Mobile}}</text>
					<u-tag v-if="item.IsDefault == 1" class="flex-shrink-0 ml-[auto]" text="默认" size="mini"></u-tag>
				</view>
			</template>
			<template v-slot:label>
				<view class="text-[14px] text-[#999999] mt-[4px]">
					<text>{{item.AreaStr}}</text>
					<text class="ml-[16px]">{{item.Street}}</text>
				</view>
			</template>
		</u-cell>
		<u-empty mode="address" v-if="list.length == 0"></u-empty>
		<u-gap height="60"></u-gap>
	</view>
	<view class="fixed flex flex-col justify-center left-0 bottom-0 w-full h-[60px] box-content bg-[#f8f8f8] pb-safe-nopadding">
		<view class="px-[16px]">
			<u-button @click="add" text="新增收货地址" icon="plus" iconColor="#FFFFFF" shape="circle" size="large" type="error"></u-button>
		</view>
	</view>
</template>

<script setup>
	import {computed, nextTick, ref, unref} from "vue";
	import * as api from "@/api.js";
	import * as uniapp from "@dcloudio/uni-app";
	import {useUserStore} from "@/store/config.js";
	
	const store = useUserStore();
	
	const keyword = ref('');
	const list = ref([]);
	
	const showList = computed(() => {
		if(unref(keyword)) {
			return unref(list).filter(i => i.name.indexOf(unref(keyword)) > -1 || i.area.indexOf(unref(keyword)) > -1 || i.address.indexOf(unref(keyword)) > -1);
		} else {
			return unref(list)
		}
	})
	
	const clear = () => {
		keyword.value = ''
	}
	
	const itemClick = item => {
		const route = getCurrentPages()[getCurrentPages().length - 2];
		if(route && route.route == "pages/order/orderConfirm") {
			//退回
			uni.$emit('addressChange',item);
			uni.navigateBack();
		} else {
			uni.navigateTo({
				url:`/pages/address/edit?mode=edit&data=${encodeURIComponent(JSON.stringify(item))}`
			})
		}
	}
	
	const add = () => {
		uni.navigateTo({
			url:`/pages/address/edit?mode=add`
		})
	}
	
	uniapp.onShow(() => {
		keyword.value = '';
		getData();
	})
	
	uniapp.onPullDownRefresh(() => {
		getData();
	})
	
	const getData = async () => {
		uni.showLoading();
		const result = await api.getAddressList(store.user.UserID);
		uni.hideLoading();
		await nextTick();
		if(result[1]) {
			uni.showToast({
				icon:'none',
				title:result[1]
			})
		} else {
			list.value = result[0];
		}
	}
</script>

<style>
</style>